#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <Windows.h>
#include "../Common/Thread.h"
#include "../Common/ThreadManager.h"

class Data
{
public:
    Data(std::string filename, std::string content)
        : filename(filename), content(content), changed(true)
    {
        InitializeCriticalSection(&cs_c);
        InitializeCriticalSection(&cs_s);
    }
    ~Data()
    {
        DeleteCriticalSection(&cs_c);
        DeleteCriticalSection(&cs_s);
    }

public:
    void change(std::string newContent)
    {
        EnterCriticalSection(&cs_c);

        content = newContent;
        changed = true;

        LeaveCriticalSection(&cs_c);
    }

    void save()
    {
        EnterCriticalSection(&cs_s);

        if(!changed)
        {
            LeaveCriticalSection(&cs_s);
            return;
        }
        doSave();
        changed = false;

        LeaveCriticalSection(&cs_s);
    }

    void doSave()
    {   
        CThread* t = CThreadManager::getInstance()->getThread((unsigned)GetCurrentThreadId());
        printf("%s calls doSave, content = %s\n", t->getName().c_str() , content.c_str());
        std::fstream fs;
        fs.open(filename, std::fstream::out);
        fs << content;
        fs.close();        
    }

private:
    const std::string filename;
    std::string content;
    bool changed;
    CRITICAL_SECTION cs_s;
    CRITICAL_SECTION cs_c;
};